//
//  NewHomeViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/7/14.
//  Copyright © 2017年 lianfu. All rights reserved.
//  CLLocationManagerDelegate
import Foundation
import UIKit
import Alamofire
import CoreLocation
import Kingfisher


@available(iOS 9.0, *)
@objc class NewHomeViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource,  CarouselViewDataSourse, CarouselViewDelegate, UIScrollViewDelegate, CLLocationManagerDelegate {

    //@IBOutlet weak var tableHight: NSLayoutConstraint!
    
    @IBOutlet weak var preCityCtrItem: UIBarButtonItem!
    @IBAction func preCityCtrItem(_ sender: UIBarButtonItem) {
        let sb = UIStoryboard(name: "Main", bundle:nil)
        let secondViewController = sb.instantiateViewController(withIdentifier: "city") as! UINavigationController
        self.present(secondViewController, animated: true, completion: nil)//CitySelectorViewController
//        let sb = UIStoryboard(name: "Main", bundle:nil)
//        let vc = sb.instantiateViewController(withIdentifier: "shopping") as! UINavigationController
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
//    @IBAction func unwindToHomeScreen(segue:UIStoryboardSegue) {
//    }
    let tScrollView = UIScrollView()

    let ref = UIRefreshControl()
    let locationManager = CLLocationManager()
    var currLocation: CLLocation!
    lazy var lat:Double = 0.0
    lazy var long:Double = 0.0
    var dingweicity = ""
    
    var shopArr = NSArray()

    
    var imgAr = [String]()
    var isTarget = true
    var targetRect = CGRect()
    
    
    @IBOutlet weak var testPage: UIView!
    
    
    
    
    @IBOutlet weak var DianpuTableView: UITableView!

    
    
    @IBOutlet weak var scrollPage: CarouselView!
    
    //@IBOutlet weak var totalscroll: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(NewHomeViewController.re(title:)), name: NSNotification.Name(rawValue: "NewHomeReload"), object: nil)
        self.view.addSubview(tScrollView)
        tScrollView.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height - 64)
        tScrollView.addSubview(testPage)
        testPage.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height:170)
        tScrollView.addSubview(DianpuTableView)
        DianpuTableView.frame = CGRect(x: 0, y: 150, width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height - 42)
        scrollPage.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height:170)
        
        
        DianpuTableView.tag = 101
        tScrollView.isScrollEnabled = false
        scrollPage.cellPerPage = 1
        scrollPage.type = .loop
        scrollPage.dataSource = self
        scrollPage.delegate = self
        scrollPage.pagingType = .cellLimit
        scrollPage.direction = .horizontal
        scrollPage.reload()
        scrollPage.autoScroll(2, increase: true)
        
        DianpuTableView.tableFooterView = UIView(frame:CGRect.zero)
        DianpuTableView.showsVerticalScrollIndicator = false
        
        ref.backgroundColor = UIColor.clear
        ref.tintColor = UIColor.darkGray
        ref.addTarget(self, action: #selector(refreshaction), for: .valueChanged)
        DianpuTableView.addSubview(ref)
        automaticallyAdjustsScrollViewInsets = false
      
        
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
        initLocation()
        ref.beginRefreshing()
        //getshopinfor()
               getimg()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
//    func re(title:Notification){
//        self.DianpuTableView.reloadData()
//    }
    
    func refreshaction() {
        getshopinfor()
    }
    
    func initLocation() {
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
        
    }
    
//    func LonLatToCity() {
//
//        let geocoder: CLGeocoder = CLGeocoder()
//        geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void in
//
//            if error == nil {
//                let array = placemark! as NSArray
//                let mark = array.firstObject as! CLPlacemark
//                let ci: String = (mark.addressDictionary! as NSDictionary).value(forKey: "City") as! String
//                self.dingweicity = ci
//                self.preCityCtrItem.title = ci
//                print(ci)
//                print(ci)
//                self.getshopinfor()
//
//            } else {
//                self.ref.endRefreshing()
//                self.getshopinfor()
//                self.noticeError("定位失败", autoClear: true, autoClearTime: 2)
//            }}}
 
    
    func getshopinfor(){
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        var x = UserDefaults.standard.object(forKey: "cityKey") as? String
        var y = UserDefaults.standard.object(forKey: "cityKey") as? String
        if y == nil {
            y = ""
        }
        if x == nil {
            x = "选择城市"
        }
        preCityCtrItem.title = x
        let parameters = ["type":"all","lng": "\(long)","lat":"\(lat)","localcity":"\(y!)"]
            let urlString = "https://www.beidikeji.com/life/public/jiekou/shangquanjson?"
        manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
                switch Request.result {
                case .success:
                    
                    let json = JSON(data: Request.data!)
                    self.shopArr = json.arrayObject! as NSArray
                    DispatchQueue.main.async(execute: {
                        self.DianpuTableView.reloadData()
                        self.ref.endRefreshing()
                    })
                case .failure:
                    DispatchQueue.main.async(execute: { () -> Void in
                    self.ref.endRefreshing()
                    self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
                    })
            }}}

    func getimg(){
        let urlString = "https://www.beidikeji.com/life/public/jiekou/indeximg?"
            let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 45
            manager.request(urlString,method:.post).responseJSON {Request in
            switch Request.result {
            case .success:

                DispatchQueue.main.async(execute: {
                let json = JSON(data: Request.data!).arrayObject
                let im = json as! [String]
                self.imgAr = im
                    if self.imgAr.count == 0 {
                        self.testPage.frame = CGRect(x: 0, y: 0, width: mainScreenW, height:0)
                        self.DianpuTableView.frame = CGRect(x: 0, y: -106, width: mainScreenW, height:mainScreenH + 106)
                    self.scrollPage.reload()
                        self.DianpuTableView.reloadData()
                    } else if self.imgAr.count != 0 {
//                        self.testPage.frame = CGRect(x: 0, y: 0, width: mainScreenW, height:0)
//                        self.DianpuTableView.frame = CGRect(x: 0, y: -106, width: mainScreenW, height:mainScreenH + 106)
                        self.scrollPage.reload()
                        //self.DianpuTableView.reloadData()
                    }
                })
            case .failure: break
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location:CLLocation = locations[locations.count-1]
        currLocation = locations.last!
        //判断是否为空
        if location.horizontalAccuracy > 0 {
            lat = Double(String(format: "%.5f", location.coordinate.latitude))!
            long = Double(String(format: "%.5f", location.coordinate.longitude))!
            getshopinfor()
            //LonLatToCity()
            //停止定位
            self.locationManager.stopUpdatingLocation()
        }
    }
    
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        //print("error:: \(error)")
    }

 
    
    func re(title:NSNotification){
        self.ref.beginRefreshing()
        initLocation()
        //getshopinfor()
    }
    
    
    
    func numberOfView(_ carousel: CarouselView) -> Int {
        return Int(imgAr.count)
    }
    
    func carousel(_ carousel:CarouselView, viewForIndex index:Int) -> UIView? {
        
        //let padding:CGFloat = 20
        let v = UIView()
        v.backgroundColor = UIColor.white
        let img = UIImageView()
        
        let url = URL(string:imgAr[index])
        img.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
            if error == nil && url == urls {
                v.addSubview(img)
                img.translatesAutoresizingMaskIntoConstraints = false
                let w = img.heightAnchor.constraint(equalTo: v.heightAnchor, multiplier: 1, constant: 0)
                let h = img.widthAnchor.constraint(equalTo: v.widthAnchor, multiplier: 1, constant: 0)
                let cx = img.centerXAnchor.constraint(equalTo: v.centerXAnchor)
                let cy = img.centerYAnchor.constraint(equalTo: v.centerYAnchor)
                NSLayoutConstraint.activate([w, h, cx, cy])
            } else {
                
            }})
        return (index % 6 == 0 && index != 0) ? nil : v
    }

    // CarouselViewDelegate
    func carousel(_ carousel: CarouselView, didScrollFrom: Int, to: Int) {
        //print("CarouselView didScrollFrom \(didScrollFrom) \(to)")
    }
    
    func carousel(_ carousel: CarouselView, scrollFrom: Int, to: Int, progress: CGFloat) {
        //print("CarouselView scrollFrom \(scrollFrom) \(to) \(progress)")
    }
    
    func carousel(_ carousel: CarouselView, didTapAt cell: Int) {
        //print("CarouselView didTapAt \(cell)")
    }

    
    

    
    func setup(cell: NewHomeTableViewCell, atIndexPath indexPath: IndexPath) {
        let result = shopArr[indexPath.row] as! NSDictionary
        let  or = result["shopimg"] as? String
        let url = URL(string:or!)
        //cell.titleImage.layer.cornerRadius = 30
        if cell.titleImage.kf.webURL != url {
            let cellFrame = self.DianpuTableView.rectForRow(at: indexPath)
            var shouldLoadImage = true
            if self.isTarget && !self.targetRect.intersects(cellFrame) {
                let image = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: or!, options: nil)
                if image == nil {
                    shouldLoadImage = false
                }
            }
            if shouldLoadImage {
                cell.titleImage.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
                    if error == nil && url == urls {
                    }})}}}


    
    
    
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                    return shopArr.count
                }
                
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "NewHomeTableViewCell", for: indexPath) as! NewHomeTableViewCell
                    let result = shopArr[indexPath.row] as! NSDictionary
    
                    //cell.titleImage.layer.cornerRadius = 30
                    cell.titleLabel.text = result["shopname"] as? String
                    cell.seLabel.text = result["shoplabel"] as? String
                    cell.thLabel.text = result["tel"] as? String
                    cell.foLabel.text = result["address2"] as? String
                    self.setup(cell: cell, atIndexPath: indexPath)
                    return cell
                }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        DianpuTableView.deselectRow(at: indexPath, animated: false)
        let result = shopArr[indexPath.row] as! NSDictionary
        dpid = "\(result["id"]!)"
        let sb = UIStoryboard(name: "Main", bundle:nil)
        let secondViewController = sb.instantiateViewController(withIdentifier: "DianpuViewController") as! DianpuViewController
        //self.present(secondViewController, animated: true, completion: nil)
        //        let sb = UIStoryboard(name: "Main", bundle:nil)
        //        let vc = sb.instantiateViewController(withIdentifier: "shopping") as! UINavigationController
                self.navigationController?.pushViewController(secondViewController, animated: true)
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        self.targetRect = CGRect(x: targetContentOffset.pointee.x, y: targetContentOffset.pointee.y, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
        self.isTarget = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.isTarget = false
        self.loadImageForVisibleCells()
    }
    
    func loadImageForVisibleCells() {
        let visibleCells = self.DianpuTableView.visibleCells
        for cell in visibleCells {
            self.setup(cell: cell as! NewHomeTableViewCell, atIndexPath: self.DianpuTableView.indexPath(for: cell)!)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.tag == 101 {
        if scrollView.contentOffset.y < 175 && scrollView.contentOffset.y > 0 {
            //tableHight.constant = CGFloat(UIScreen.main.bounds.height - 42)
            //DianpuTableView.contentSize.height = UIScreen.main.bounds.height - 42
            tScrollView.contentOffset.y = scrollView.contentOffset.y
        } else if scrollView.contentOffset.y < 0 {
            tScrollView.contentOffset.y = scrollView.contentOffset.y
        }

        }
        
    }
}


